package util;

import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;

import java.util.List;

public class NodeDragUtil {

    public static void addNodeDragListener(Node node, AnchorPane parent){
        new DragListener(node,parent).enableDrag(node);
    }

    public static class DragListener implements EventHandler<MouseEvent> {
        private double xOffset = 0;
        private double yOffset = 0;
        private Node node;
        private AnchorPane parent;

        private DragListener(Node node, AnchorPane parent) {
            this.parent = parent;
            this.node = node;
        }

        @Override
        public void handle(MouseEvent event) {
            event.consume();
            if (event.getEventType() == MouseEvent.MOUSE_PRESSED) {
                xOffset = event.getX();
                yOffset = event.getY();
            } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
                double x = (node.getTranslateX()+event.getX() - xOffset);
                double y = (node.getTranslateY()+event.getY() - yOffset);
                /*double parent_width = parent.widthProperty().doubleValue();
                double parent_height = parent.heightProperty().doubleValue();*/
                node.setTranslateX(x);
                node.setTranslateY(y);
                /*if(x>0 && y>0 && x<=parent_width && y<=parent_height) {

                }else if(x<0 && y<0){
                    node.setTranslateX(x<0 ? 0 : x);
                    node.setTranslateY(y<0 ? 0 : y);
                }*/
            }
        }

        private void enableDrag(Node node) {
            node.setOnMousePressed(this);
            node.setOnMouseDragged(this);
        }
    }
}
